package com.caocaog.market.finance.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.finance.calculation.Calculate;
import com.caocaog.market.finance.entity.*;
import com.caocaog.market.finance.pay.FinanceUnionPay;
import com.caocaog.market.finance.service.*;
import com.caocaog.market.finance.vo.SysCheckVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.domain.QueryRequest;
import org.jeecg.common.system.query.PageGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.LoginUserSite;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liguang
 * @version 1.0.0
 * @Project jeecg-boot
 * @Package com.caocaog.market.finance.controller
 * @ClassName MkBillBaseController.java
 * @createTime 2021年12月03日 19:37:00
 * @Description 账务模块——账单信息
 */
@Api(tags = "账务模块——账单信息")
@RestController
@RequestMapping("/finance/bill")
@Slf4j
@SuppressWarnings("all")

public class MkBillController {
    @Autowired
    private MkBillBaseService billBaseService;
    @Autowired
    private MkBillHistoryService billHistoryService;
    @Autowired
    private CommonAPI commonAPI;
    @Autowired
    private MkBillLineHistoryService billLineHistoryService;
    @Autowired
    private MkBillLineService billLineService;
    @Autowired
    private FinanceUnionPay financeUnionPay;
    @Autowired
    private IMkBillChangeService billChangeService;


    @AutoLog(value = "账务模块——账单信息——查询所有账单")
    @GetMapping(value = "/list")
    @ApiOperation(value = "查询所有账单", notes = "查询所有账单")
    public Result list(MkBillBase billBase, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize, HttpServletRequest req) {
        /**
         * 1、判断当前登录用户是  系统用户  还是  分站用户   还是  商家用户
         * 2、如果是系统用户则查询所有账单，如果是分站用户只查询该分站下的账单，如果是商家用户则查询该商家下的账单
         */

        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer userType = null == currentUser.getUserType() ? 1 : currentUser.getUserType();
        if (userType == MarketConstant.USER_TYPE_SITE) {
            /**
             *  当前登录用户为分站用户，需要取分站的信息
             */
            LoginUserSite loginUserSite = commonAPI.getSiteByName(currentUser.getUsername());
            String siteId = loginUserSite.getId();
            System.out.println("分站id_______>   " + siteId);
            billBase.setSiteId(siteId);
        }
        if (userType == MarketConstant.USER_TYPE_MERCHANT) {
            /**
             *  当前登录用户为商家用户，需要取商家id
             */
            String merchantId = currentUser.getMerchantId();
            System.out.println("商家id————————————》  " + merchantId);
            billBase.setMerchantId(merchantId);
            /** 获取当前用户所选择的门店
             String shopId = currentUser.getCurrentSelectedShopId();
             System.out.println("shopId--------->    "+shopId);
             if(StringUtils.isNotBlank(shopId)){
             billBase.setMerchantId(shopId);
             }*/
        }
        Result<IPage<MkBillBase>> result = new Result<IPage<MkBillBase>>();
        Page<MkBillBase> page = new Page<MkBillBase>(pageNo, pageSize);
        IPage<MkBillBase> pageList = billBaseService.findForPage(page, billBase);
        log.info("查询当前页：" + pageList.getCurrent());
        log.info("查询当前页数量：" + pageList.getSize());
        log.info("查询结果数量：" + pageList.getRecords().size());
        log.info("数据总数：" + pageList.getTotal());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @AutoLog(value = "账务模块——账单信息——添加账单信息")
    @PostMapping(value = "/insert")
    @ApiOperation(value = "添加账单信息", notes = "保存账单信息时，会同时存储到MkBillHistory对象中一份")
    public Result insert(@RequestBody MkBillHistory billHistory) {
        Result relt = new Result();
        relt = validBill(relt, billHistory);
        if (!relt.isSuccess()) {
            //如果验证失败，直接返回
            return relt;
        }
        int count = billHistoryService.insertBillAndHistory(billHistory);
        System.out.println("count---->  " + count);
        log.info("插入的条数：" + count);
        if (count == 0) {
            // 返回 0 表示同时插入mk_bill_base和mk_bill_history两张表失败
            relt.setSuccess(false);
            return relt;
        }
        relt.setSuccess(true);
        return relt;
    }

    /**
     * 账务审核，同意退款，状态修改为”待退款“
     *
     * @param relt
     * @param billHistory
     * @return
     */
    @AutoLog(value = "账务模块——账单信息——同意退款")
    @PostMapping(value = "/agreeRefund")
    @ApiOperation(value = "同意退款", notes = "账务同意退款后，账单状态修改为”待退款“，同时在账务账单表中再存一条数据")
    public Result agreeRefund(@RequestParam("orderNo") String orderNo) {
        Result relt = new Result();
        /**
         * 校验信息：
         *      订单号不能为空
         */
        if (StringUtils.isBlank(orderNo)) {
            relt.setMessage("订单号不能为空");
            relt.setSuccess(false);
            return relt;
        }
        int count = billBaseService.agreeRefund(orderNo);
        if (count == 0) {
            relt.setMessage("同意退款失败");
            relt.setSuccess(false);
            return relt;
        }
        relt.setMessage("同意退款失败");
        relt.setSuccess(true);
        return relt;
    }

    /**
     * @param relt
     * @param billHistory
     * @return
     */
    @AutoLog(value = "账务模块——账单信息——退款成功")
    @PostMapping(value = "/refundSuccess")
    @ApiOperation(value = "退款成功", notes = "账务向退款客户退钱，如果退款成功账单状态修改为”已退款“，同时在账务账单表中再存一条数据")
    public Result refundSuccess(@RequestParam("orderNo") String orderNo) {
        Result relt = new Result();
        /**
         * 校验信息：
         *      订单号不能为空
         */
        if (StringUtils.isBlank(orderNo)) {
            relt.setMessage("订单号不能为空");
            relt.setSuccess(false);
            return relt;
        }
        int count = billBaseService.refundSuccess(orderNo);
        if (count == 0) {
            relt.setMessage("退款操作执行失败");
            relt.setSuccess(false);
            return relt;
        }
        relt.setMessage("退款操作执行成功");
        relt.setSuccess(true);
        return relt;
    }


    @AutoLog(value = "账务模块——账单信息——执行结算操作")
    @PostMapping(value = "/settle")
    @ApiOperation(value = "执行结算操作", notes = "订单达到结算条件之后，查询出来并进行结算")
    public Result settle() {
        Result relt = new Result();
        /**
         *  结算天数（settlement_time字段，单位是天）、总部的抽成比例（sys_rake_rate字段/100）是从mk_site_basic中取的；
         *  分站抽成  是从mk_shop_basic中取的 commission_rate  字段
         *      1、查询出所有待结算的账单根据系统给每个分站设置的结算天数判断该账单是否可以进行结算
         *          1.1 查询出所有待结算的账单
         *          1.2 看这些待结算的账单属于哪个分站  查询出该分站的待结算时间以及抽成比例
         *          1.3 进入第2步进行计算
         *
         *      2、根据每个订单所属的商家、分站（抽成比例）  以及   系统(抽成比例)  来进行分成计算
         *
         *      3、每个单子的抽成比例、金额算好之后 存入mk_bill_line 以及  mk_bill_history表中
         */
        MkBillBase billBase = new MkBillBase();
        // 查询待结算的账单信息
        billBase.setPayStatus(MarketConstant.FINANCE_PAY_STATUS_DJS);
        List<MkBillBase> billList = billBaseService.findAllForNoPage(billBase);
        /**
         * 调用结算方法进行结算
         */
        List<MkBillLineHistory> lines = Calculate.compute(billList);
        /**
         * 存订单行以及订单行历史
         * */
        int count = billLineHistoryService.insertBillLineAndHistory(billList,lines);
        if(count<1){
            relt.setSuccess(false);
            relt.setMessage("结算动作执行失败");
            return relt;
        }
        relt.setSuccess(true);
        relt.setMessage("结算动作执行成功");
        return relt;
    }

    /**
     * 所有收入数据
     *
     * @param relt
     * @param billHistory
     * @return
     */
    @AutoLog(value = "账务模块——账单信息——系统/分站/商家 的已结算的收入数据")
    @GetMapping(value = "/withdrawCash/income/listByType")
    @ApiOperation(value = "系统/分站/商家 的已结算的收入数据", notes = "系统/分站/商家 的已结算的收入数据")
    public Result withdrawCashIncomList(MkBillLine billLine, QueryRequest queryRequest, HttpServletRequest req) {
        return incomeOrSysCheckList(billLine, queryRequest, req);
    }
    /**
     *   提现审核列表数据
     *
     * @param relt
     * @param billHistory
     * @return
     */
    @AutoLog(value = "账务模块——账单信息——系统/分站/商家 的提现审核列表数据")
    @GetMapping(value = "/withdrawCash/sysCheck/list")
    @ApiOperation(value = "系统/分站/商家 的提现审核列表数据", notes = "系统/分站/商家 的提现审核列表数据")
    public Result withdrawCashSysCheck(MkBillLine billLine, QueryRequest queryRequest, HttpServletRequest req) {
        int[] ints = new int[]{2,3,4,5,6};
        billLine.setWithdrawCashStatuses(ints);
//        billLine.setWithdrawCashStatuses("line.withdraw_cash_status=2 or line.withdraw_cash_status=3 or line.withdraw_cash_status=4 or line.withdraw_cash_status=6");
        queryRequest.setColumn("id");
        return incomeOrSysCheckList(billLine, queryRequest, req);
    }
    private Result incomeOrSysCheckList(MkBillLine billLine, QueryRequest queryRequest, HttpServletRequest req){
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer userType = currentUser.getUserType();
        if (userType == MarketConstant.USER_TYPE_SITE) {
            /**
             *  当前登录用户为分站用户，需要取分站的信息
             */
            LoginUserSite loginUserSite = commonAPI.getSiteByName(currentUser.getUsername());
            String siteId = loginUserSite.getId();
            System.out.println("分站id_______>   " + siteId);
            billLine.setSiteId(siteId);
            billLine.setType(MarketConstant.FINANCE_BILL_LINE_TYPE_SITE);
        }
        if (userType == MarketConstant.USER_TYPE_MERCHANT) {
            /**
             *  当前登录用户为商家用户，需要取商家id
             */
            String merchantId = currentUser.getMerchantId();
            System.out.println("商家id————————————》  " + merchantId);
            billLine.setMerchantId(merchantId);
            billLine.setType(MarketConstant.FINANCE_BILL_LINE_TYPE_SHOP);
        }
        Result<IPage<MkBillLine>> result = new Result<IPage<MkBillLine>>();
        Page<MkBillLine> page = PageGenerator.createPageSort(queryRequest);
        IPage<MkBillLine> pageList = billLineService.findForPage(page, billLine);
        if(null!=pageList && pageList.getSize()>0){
            QueryWrapper<MkBillLine> qw = new QueryWrapper<>();
            for (MkBillLine bl : pageList.getRecords()) {
                qw.clear();
                qw.eq("order_no",bl.getOrderNo());
                qw.eq("type",bl.getType());
                int num = billLineService.numByCondation(qw);
                if(num>1){
                    String mark = oConvertUtils.isEmpty(bl.getMark())? "" : bl.getMark();
                    bl.setMark(mark+" 总共结算"+num+"次；其中，重复结算"+(num-1)+"次，重复结算的钱数不计入账户余额");
                    log.info("订单备注：-----"+bl.getMark());
                }
            }
        }
        log.info("查询当前页：" + pageList.getCurrent());
        log.info("查询当前页数量：" + pageList.getSize());
        log.info("查询结果数量：" + pageList.getRecords().size());
        log.info("数据总数：" + pageList.getTotal());

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @AutoLog(value = "账务模块——账单信息——系统/分站/商家 的批量提现审核列表数据")
    @GetMapping(value = "/withdrawCash/sysCheck/batchList")
    @ApiOperation(value = "系统/分站/商家 的批量提现审核列表数据", notes = "系统/分站/商家 的批量提现审核列表数据")
    public Result withdrawCashSysCheckbatchList(MkBillLine billLine, QueryRequest queryRequest, HttpServletRequest req) {
        List<SysCheckVo> list = billLineService.findSysCheckVoList();
        if (oConvertUtils.listIsEmpty(list)){return Result.error("暂无要审核的数据");}
        return Result.OK(list);
    }

    @RequestMapping(value = "/withdrawCash/sysCheck/exportXls")
    public ModelAndView exportXls(MkBillLine billLine, HttpServletRequest req) {
        int[] ints = new int[]{2,3,4,5,6};
        billLine.setWithdrawCashStatuses(ints);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        QueryRequest queryRequest = new QueryRequest();
        queryRequest.setPageSize(1000);
        queryRequest.setColumn("id");
        IPage<MkBillLine> pageList = (IPage<MkBillLine>)incomeOrSysCheckList(billLine, queryRequest, req).getResult();
        // 导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "系统审核列表");
        mv.addObject(NormalExcelConstants.CLASS, MkBillLine.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("系统审核列表数据", "", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList.getRecords());
        return mv;
    }

    @AutoLog(value = "账务模块——账单信息——系统/分站/商家 已结算过后的余额")
    @GetMapping(value = "/withdrawCash/income/balance")
    @ApiOperation(value = "系统/分站/商家 已结算过后的余额", notes = "系统/分站/商家 已结算过后的余额")
    public Result withdrawCashBalance(MkBillLine billLine,HttpServletRequest req){
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer userType = currentUser.getUserType();
        if (userType == MarketConstant.USER_TYPE_SITE) {
            /**
             *  当前登录用户为分站用户，需要取分站的信息
             */
            LoginUserSite loginUserSite = commonAPI.getSiteByName(currentUser.getUsername());
            String siteId = loginUserSite.getId();
            System.out.println("分站id_余额______>   " + siteId);
            billLine.setSiteId(siteId);
            billLine.setType(MarketConstant.FINANCE_BILL_LINE_TYPE_SITE);
        }
        if (userType == MarketConstant.USER_TYPE_MERCHANT) {
            /**
             *  当前登录用户为商家用户，需要取商家id
             */
            String merchantId = currentUser.getMerchantId();
            System.out.println("商家id—余额——————————》  " + merchantId);
            billLine.setMerchantId(merchantId);
            billLine.setType(MarketConstant.FINANCE_BILL_LINE_TYPE_SHOP);
        }
        Result<MkBillLine> result = new Result<MkBillLine>();
        int[] ins = new int[]{MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_DTX,MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_YSQDSH,
                MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_SHTGDZZ,MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_BH};
        billLine.setWithdrawCashStatuses(ins);

        List<MkBillLine> billLines = billLineService.findForPage(billLine);
        MkBillLine mkBillLineBalance = new MkBillLine();
        // 总余额，状态为：1，2，3，4
        BigDecimal zDecimal = new BigDecimal(0.00);
        // 已结算待申请提现 1
        BigDecimal dtxDecimal = new BigDecimal(0.00);
        // 已申请提现待总部审核 2
        BigDecimal ysqdshDecimal = new BigDecimal(0.00);
        // 已申请提现总部审核通过的钱数，状态为：3
        BigDecimal shtgdzzDecimal = new BigDecimal(0.00);
        // 提现申请被驳回  4
        BigDecimal bhDecimal = new BigDecimal(0.00);

        BigDecimal newTotal =new BigDecimal(0.00);

        // 总部的收益
        BigDecimal sysDecimal = new BigDecimal(0.00);
        List<String> sysIdsList = new ArrayList<String>();
        List<String> otherIdsList = new ArrayList<String>();
        for (MkBillLine mkBillLine : billLines){
            String amount = mkBillLine.getRakeAmount();
            BigDecimal decimal = new BigDecimal(amount);
            if(null!=otherIdsList && otherIdsList.size()>0 && otherIdsList.contains(mkBillLine.getOrderNo())){
                continue;
            }
            zDecimal = zDecimal.add(decimal);
            int withdrawCashStatus = mkBillLine.getWithdrawCashStatus();
            if(mkBillLine.getType()==MarketConstant.USER_TYPE_SYSTEM){
                if(null !=sysIdsList && sysIdsList.size()>0 && sysIdsList.contains(mkBillLine.getOrderNo())){
                    continue;
                }
                sysIdsList.add(mkBillLine.getOrderNo());
                // 计算总部的收益
                sysDecimal = sysDecimal.add(decimal);
                continue;
            }else{
                otherIdsList.add(mkBillLine.getOrderNo());
            }
            if(withdrawCashStatus==MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_DTX){
                // 已结算待申请提现
                dtxDecimal = dtxDecimal.add(decimal);
                continue;
            }
            if(withdrawCashStatus==MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_YSQDSH){
                // 已申请提现，待总部审核
                ysqdshDecimal = ysqdshDecimal.add(decimal);
                continue;
            }
            if(withdrawCashStatus==MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_SHTGDZZ){
                // 提现申请已审核通过，总部待转账
                shtgdzzDecimal = shtgdzzDecimal.add(decimal);
                continue;
            }
            if(withdrawCashStatus==MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_BH){
                bhDecimal = bhDecimal.add(decimal);
                continue;
            }
        }
        if(userType==MarketConstant.USER_TYPE_SYSTEM){
            mkBillLineBalance.setSysBalance(String.valueOf(sysDecimal));
        }else{
            // 账户总余额：（去除已提现的）
            mkBillLineBalance.setTotalBalance(String.valueOf(zDecimal));
            // 待提现
            mkBillLineBalance.setDtxBalance(String.valueOf(dtxDecimal));
            // 已申请提现待总部审核
            mkBillLineBalance.setYsqdshBalance(String.valueOf(ysqdshDecimal));
            // 提现申请审核通过待转账
            mkBillLineBalance.setShtgdzzBalance(String.valueOf(shtgdzzDecimal));
            // 提现申请被驳回
            mkBillLineBalance.setBhBalance(String.valueOf(bhDecimal));

            mkBillLineBalance.setDtxBalance(String.valueOf(dtxDecimal.add(bhDecimal)));

        }
        result.setSuccess(true);
        result.setResult(mkBillLineBalance);
        return result;
    }
    /**
     * 根据账单行id查询账单行历史记录
     */
    @AutoLog(value = "账务模块——账单信息——根据账单行id查询账单行的历史记录信息")
    @GetMapping(value = "/withdrawCash/income/lineHistoryByBillLineId")
    @ApiOperation(value = "根据账单行id查询账单行的历史记录信息", notes = "根据账单行id查询账单行的历史记录信息")
    public Result lineHistoryByBillLineId(String billLineId){
        Result relt = new Result();
        List<MkBillLineHistory> billLineHistories = billLineHistoryService.findByBillLineId(billLineId);
        try{
            relt.setResult(billLineHistories);
            relt.setSuccess(true);
        }catch (Exception e){
            relt.setSuccess(false);
        }
        return relt;
    }
    /**
     * 根据订单号查询该订单号所对应的账单行信息
     */
    @AutoLog(value = "账务模块——账单信息——根据订单号查询该订单号所对应的账单行信息")
    @GetMapping(value = "/withdrawCash/income/billLineByOrderNo")
    @ApiOperation(value = "根据订单号查询该订单号所对应的账单行信息", notes = "根据订单号查询该订单号所对应的账单行信息")
    public Result lineByBillOrderNo(String orderNo){
        Result relt = new Result();
        MkBillLine line = new MkBillLine();
        line.setOrderNo(orderNo);
        List<MkBillLine> billLines = billLineService.findForPage(line);
        try{
            relt.setResult(billLines);
            relt.setSuccess(true);
        }catch (Exception e){
            relt.setSuccess(false);
        }
        return relt;
    }
    /**
     * 根据账单行id查询该账单行信息
     */
    @AutoLog(value = "账务模块——账单信息——根据账单行id查询该账单行信息")
    @GetMapping(value = "/withdrawCash/income/billLineByBillLineId")
    @ApiOperation(value = "根据账单行id查询该账单行信息", notes = "根据账单行id查询该账单行信息")
    public Result lineByBillLineId(String billLineId){
        Result relt = new Result();
        System.out.println("billlineId------>  "+billLineId);

        MkBillLine line = billLineService.findById(billLineId);
        try{
            relt.setResult(line);
            relt.setSuccess(true);
        }catch (Exception e){
            e.printStackTrace();
            relt.setSuccess(false);
        }
        return relt;
    }


    /**
     *  缺的方法：
     *          第一个方法：全部审核通过            更新状态为：审核成功待转账
     *          第二个方法：单个审核通过            更新状态为：审核成功待转账
     *          第三个方法：全部驳回，带原因        更新状态为：驳回
     *          第四个方法：单个驳回，带原因        更新状态为：驳回
     *          第五个方法：账务转账成功           更新状态为：已提现
     *          第六个方法：账务转账失败           更新状态为：待提现
     * @param relt
     * @param billHistory
     * @return
     */



    @AutoLog(value = "账务模块——账单信息——分站/商家 用户发出提现申请，总部审核(批量审核)")
    @PostMapping(value="/withdrawCash/income/application/batchAuditThree")
    @ApiOperation(value = "分站/商家 总部审核", notes = "分站/商家 用户发出提现申请，总部审核(批量审核)")
    public Result batchAuditThree(@RequestBody List<SysCheckVo> sysCheckVos){
        if (sysCheckVos.size()<1){
            return Result.error("请至少选择一个待审核的账单哟!");
        }
        this.billLineService.batchWithdrawCashApplication(sysCheckVos,3);
        return Result.OK("操作成功");
    }
    @AutoLog(value = "账务模块——账单信息——分站/商家 用户发出提现申请，总部审核(批量审核-驳回)")
    @PostMapping(value="/withdrawCash/income/application/batchAuditFour")
    @ApiOperation(value = "分站/商家 总部审核(批量审核-驳回)", notes = "分站/商家 用户发出提现申请，总部审核(批量审核-驳回)")
    public Result checks(@RequestBody List<String> idList, HttpServletRequest req) {
        if (idList.size() < 1) {
            return Result.error("请至少选择一个待审核的账单哟!");
        }
        Integer count = billLineService.batchWithdrawById(idList);
        return Result.OK("操作成功", count);
    }

    /**
     * 第一个方法：全部审核通过            更新状态为：审核成功待转账
     * 第二个方法：单个审核通过            更新状态为：审核成功待转账
     *
     * @param relt
     * @param billHistory
     * @return
     */
    @AutoLog(value = "账务模块——账单信息——分站/商家 用户发出提现申请，审核通过")
    @PostMapping(value="/withdrawCash/income/application/pass")
    @ApiOperation(value = "分站/商家 审核通过", notes = "分站/商家 用户发出提现申请，审核通过")
    public Result withdrawCashIncomeApplicationPass(MkBillLine billLine,HttpServletRequest req){
        billLine.setWithdrawCashStatus(MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_YSQDSH); // 已申请待审核的数据
        Result relt = new Result();
        int count = billLineService.withdrawCashApplication(billLine,MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_SHTGDZZ);
        if(count<1){
            relt.setMessage("提现申请审核通过操作失败");
            relt.setSuccess(false);
            return relt;
        }
        relt.setMessage("提现申请审核通过操作成功");
        relt.setSuccess(true);
        return relt;
    }
    /**
     *                  第三个方法：全部驳回，带原因        更新状态为：驳回
     *                 第四个方法：单个驳回，带原因        更新状态为：驳回
     * @param relt
     * @param billHistory
     * @return
     */
    @AutoLog(value = "账务模块——账单信息——分站/商家 用户发出提现申请，被驳回")
    @PostMapping(value="/withdrawCash/income/application/reject")
    @ApiOperation(value = "分站/商家 被驳回", notes = "分站/商家 用户发出提现申请，被驳回")
    public Result withdrawCashIncomeApplicationReject(MkBillLine billLine,HttpServletRequest req){
        billLine.setWithdrawCashStatus(MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_YSQDSH); // 已申请待审核的数据
        Result relt = new Result();
        int count = billLineService.withdrawCashApplication(billLine,MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_DTX);
        if(count<1){
            relt.setMessage("提现申请审核通过操作失败");
            relt.setSuccess(false);
            return relt;
        }
        relt.setMessage("提现申请审核通过操作成功");
        relt.setSuccess(true);
        return relt;
    }
    /**
     *   调用支付宝接口进行转账
     *          此时，会产生两种情况：转账成功、转账失败
     * @param relt
     * @param billHistory
     * @return
     */
    @AutoLog(value = "账务模块——账单信息—分站/商家/总部 转账")
    @PostMapping(value = "/withdrawCash/income/application/transfer")
    @ApiOperation(value = "分站/商家/总部 转账", notes = "分站/商家/总部 转账")
    public Result transfer(@RequestBody MkBillLine billLine, HttpServletRequest req) {
        //todo 单笔转账 下限 上限设置
        log.info("------单笔转账-----开始:"+billLine.getId());

        /*Map resultMap = financeUnionPay.transfer("20211208143000gfy","test-name",
                "sdty_yan@163.com.test",
                "0.01","yuki 单笔转账测试",1);
        log.info("------单笔转账-----结束:"+resultMap.toString());*/

        return Result.OK(this.billLineService.transfer(billLine.getId()));
    }

    /**
     *   调用支付宝接口进行批量转账
     *          此时，会产生两种情况：转账成功、转账失败
     * @param relt
     * @param billHistory
     * @return
     */
    @AutoLog(value = "账务模块——账单信息—分站/商家/总部 转账")
    @GetMapping(value = "/withdrawCash/income/application/transferAll")
    @ApiOperation(value = "分站/商家/总部 批量转账", notes = "分站/商家/总部 批量转账")
    public Result transferAll(@RequestParam String id, HttpServletRequest req) {
        //todo 单笔转账 下限 上限设置
        log.info("------批量转账-----开始:"+Integer.valueOf(id));

        /*Map resultMap = financeUnionPay.transfer("20211208143000gfy","test-name",
                "sdty_yan@163.com.test",
                "0.01","yuki 单笔转账测试",1);
        log.info("------单笔转账-----结束:"+resultMap.toString());*/

        return Result.OK(this.billLineService.transferAll(Integer.valueOf(id)));
    }


    private Result validBill(Result relt, MkBillHistory billHistory) {
        if (null == billHistory) {
            relt.setMessage("对象不能为空；");
            relt.setSuccess(false);
            return relt;
        }
        if (StringUtils.isBlank(billHistory.getOrderNo())) {
            relt.setMessage("订单号不能为空；");
            relt.setSuccess(false);
            return relt;
        }
        if (StringUtils.isBlank(billHistory.getPaySerno())) {
            relt.setMessage("支付流水号不能为空；");
            relt.setSuccess(false);
            return relt;
        }
        if (StringUtils.isBlank(billHistory.getPayAmount())) {
            relt.setMessage("付款金额不能为空；");
            relt.setSuccess(false);
            return relt;
        }
        /**
         * new Date().getTime() 返回的是毫秒数，new Date()底层调用的也是System.currentTimeMillis()
         * System.currentTimeMillis() 返回的也是毫秒数
         * System.currentTimeMillis()  效率更高
         * 如果billHistory.getPayTime().getTime() > 当前时间   则是错误的
         */
        System.out.println("billHistory.getPayTime().getTime()=== " + billHistory.getPayTime().getTime());
        System.out.println(" System.currentTimeMillis(====  " + System.currentTimeMillis());
        if (null == billHistory.getPayTime() || billHistory.getPayTime().getTime() > System.currentTimeMillis()) {
            relt.setMessage("支付时间错误；");
            relt.setSuccess(false);
            return relt;
        }
        if (billHistory.getPayWay() != MarketConstant.FINANCE_PAY_WAY_APP && billHistory.getPayWay() != MarketConstant.FINANCE_PAY_WAY_WECHAT) {
            relt.setMessage("支付方式（渠道）错误；");
            relt.setSuccess(false);
            return relt;
        }
        relt.setMessage("成功！");
        relt.setSuccess(true);
        return relt;
    }

    /**
     *  商家app流水记录
     *    参数（只有一个） lock_version
     *          lock_version=0  查询全部
     *          lock_version=1  查询收益
     *          lock_version>1  查询最后一个版本号的记录
     * @param args
     */
    @AutoLog(value = "商家app——账务中心—流水记录专用")
    @GetMapping(value = "/withdrawCash/income/app/flowRecord")
    @ApiOperation(value = "商家app——账务中心—流水记录专用", notes = "商家app——账务中心—流水记录专用")
    public Result lsjl(MkBillLineHistory billLineHistory, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req){

        Result<IPage<MkBillLineHistory>> result = new Result<IPage<MkBillLineHistory>>();
        Page<MkBillLineHistory> page = new Page<MkBillLineHistory>(pageNo, pageSize);
        IPage<MkBillLineHistory> pageList = billLineHistoryService.flowRecord(page,billLineHistory);
        log.info("查询当前页：" + pageList.getCurrent());
        log.info("查询当前页数量：" + pageList.getSize());
        log.info("查询结果数量：" + pageList.getRecords().size());
        log.info("数据总数：" + pageList.getTotal());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;

    }


    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse("2021-12-03 08:45:12");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date.getTime());
        System.out.println(System.currentTimeMillis());
    }

    /**
     * 用户发出提现申请,走新增的方法，防止与之前审核逻辑冲突
     *
     * @param relt
     * @param billHistory
     * @return
     */
    @AutoLog(value = "账务模块——账单信息——分站/商家 用户发出提现申请")
    @PostMapping(value = "/withdrawCash/income/application")
    @ApiOperation(value = "分站/商家 用户发出提现申请", notes = "分站/商家 用户发出提现申请")
    public Result withdrawCashIncomeApplication(HttpServletRequest req) {

        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        /**
         * 判断当前申请用户是分站还是商家：
         *     明确一点：总部无需提现
         *     只有分站和商家才可以发起提现申请
         *  所以，只需要判断当前登录用户是总部还是分站即可，即：userType='2'【分站】   还是userType='3'【商家】
         */
        Integer userType = currentUser.getUserType();
        Result relt = new Result();
        /**
         * 思路：
         *      1、根据查询条查询当前登录用户的账单行，看看哪些可以提现（mk_bill_line表中 ” withdraw_cash_status=1 “ 的数据）
         *      2、查询出来之后，修改这些这些账单行的状态为 ” 2 已提出提现申请待总部审核“ ，修改成功之后，向mk_bill_line_history表中插入一条数据
         */
        MkBillLine billLine = new MkBillLine();
       /* // 只查询待提现的数据
        //billLine.setWithdrawCashStatus(MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_DTX);*/
        // 1指待提现、4指已驳回；这两种状态都可以提现
        int[] statArr = {MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_DTX,MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_BH};
        billLine.setWithdrawCashStatuses(statArr);
        if (userType == MarketConstant.USER_TYPE_SITE) {
            /**
             *  当前登录用户为分站用户，需要取分站的信息
             */
            LoginUserSite loginUserSite = commonAPI.getSiteByName(currentUser.getUsername());
            String siteId = loginUserSite.getId();
            System.out.println("分站id_______>   " + siteId);
            billLine.setType(MarketConstant.USER_TYPE_SITE);
            billLine.setSiteId(siteId);
        }
        if (userType == MarketConstant.USER_TYPE_MERCHANT) {
            /**
             *  当前登录用户为商家用户，需要取商家id
             */
            String merchantId = currentUser.getMerchantId();
            System.out.println("商家id————————————》  " + merchantId);
            billLine.setType(MarketConstant.USER_TYPE_MERCHANT);
            billLine.setMerchantId(merchantId);
        }
        int count = billLineService.applyForWithdrawCash(billLine, MarketConstant.FINANCE_BILL_LINE_WITHDRAW_CASH_YSQDSH);
        if (count < 1) {
            relt.setMessage("暂无可提现账单");
            relt.setSuccess(false);
            relt.setCode(200);
            return relt;
        }
        relt.setMessage("提现申请操作成功");
        relt.setCode(200);
        relt.setSuccess(true);
        return relt;
    }

    @GetMapping("/page/mkBillChange")
    @ApiOperation(value = "查询分站提现记录（集）分页")
    public Result<IPage<MkBillChange>> queryTransferablePage(MkBillChange mkBillChange, QueryRequest queryRequest, HttpServletRequest req) {

        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(currentUser.getUserType() != 1){
            return Result.error("请登录管理员账号",null);
        }

//        Integer type = Integer.valueOf(req.getParameter("type"));
//        String siteId = req.getParameter("siteId");
//        mkBillChange.setType(type);
//        mkBillChange.setSiteId(siteId);
        queryRequest.setColumn("ch.create_time");
        Page<MkBillChange> page = PageGenerator.createPageSort(queryRequest,false);
        return Result.OK(billChangeService.queryMkBillChangePage(page, mkBillChange));
    }


    @AutoLog(value = "账务模块——账单信息——分站/商家 总部审核")
    @PostMapping(value="/withdrawCash/income/application/check")
    @ApiOperation(value = "分站/商家 总部审核", notes = "分站/商家 用户发出提现申请，总部审核")
    public Result check(@RequestBody MkBillChange mkBillChange,HttpServletRequest req){
        LoginUser currentUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(currentUser.getUserType() != 1){
            return Result.error("请登录管理员账号");
        }
        Result relt = new Result();
//        String auditNo = DateUtils.yymmddhhmmssSSS.get().format(new Date())+nextStatus;
//        mkBillLine.setAuditNo(auditNo);
        try{
//            int count = billLineService.checkApplication(billLine);
            boolean res = billLineService.checkBillChange(mkBillChange);
            if(res){
                relt.setSuccess(true);
            }else{
                relt.setSuccess(false);
            }
        }catch (Exception e){
            relt.setSuccess(false);
        }
        return relt;
    }
}
